package common.baiduVoice;

import com.alibaba.fastjson.JSON;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * Created by asus on 2018/3/5.
 */
public class BaiduVoiceUnits {
    private static final String appKey = "hvXtsya3WtaMOA1GaKtWigGt";
    private static final String secretKey = "K7HeLk5DNIyVckXA9pQrVs2HrwNI470A";
    private static String token = "";

    /**
     * 获取token
     * @throws Exception
     */
    public static void getToken() throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("https://openapi.baidu.com/oauth/2.0/token?");
        stringBuilder.append("grant_type=client_credentials&");
        stringBuilder.append("client_id=");
        stringBuilder.append(appKey);
        stringBuilder.append("&client_secret=");
        stringBuilder.append(secretKey);
        HttpURLConnection conn = (HttpURLConnection) new URL(stringBuilder.toString()).openConnection();
        conn.setRequestMethod("GET");   //设置本次请求的方式 ， 默认是GET方式， 参数要求都是大写字母
        conn.setConnectTimeout(5000);//设置连接超时
        conn.setDoInput(true);//是否打开输入流 ， 此方法默认为true
        conn.setDoOutput(true);//是否打开输出流， 此方法默认为false
        conn.connect();//表示连接
        if (conn.getResponseCode() == 200) {
            System.out.println("连接成功");
            // 请求返回的数据
            InputStream in = conn.getInputStream();
            try {
                byte[] data1 = new byte[in.available()];
                in.read(data1);
                // 转成字符串
                Map maps = (Map) JSON.parse(new String(data1));
                token = maps.get("access_token").toString();
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } else {

        }

    }

    /**
     * 返回百度语音路径
     * @param
     * @return
     */
    public static String getUrl(){
        try {
            getToken();
            StringBuilder url=new StringBuilder();
            url.append("http://tsn.baidu.com/text2audio?cuid=56-8C-A0-EF-E7-FC&ctp=1&");
            url.append("tok=");
            url.append(token);
            url.append("&spd=4&lan=zh&vol=15&per=0&tex=");
            return url.toString();
        }catch (Exception e){
            return null;
        }
    }

    public static String downVoice(String tex){
        return null;
    }
    public static void main(String[] sr) throws Exception {
            String s= BaiduVoiceUnits.getUrl();
          System.out.print(s);
    }
}
